<template>
  <div class="fullMain" style="height: calc(100% - 50px);overflow: scroll;">
    <div style="position:fixed; width:100%; z-index:999;border:0">
      <x-header :left-options="{backText: '',showBack: false}"
                :right-options="{showMore: true}" @on-click-more="toGroupMemberPage">{{groupName}}
      </x-header>
    </div>
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert"> {{alertText}}</alert>
    </div>
    <div class="mainBg"
         style="height: calc( 100% - 52px);background-color: white;margin-top: 46px;padding-bottom: 10px">
      <div class="message_box" id="message_box" v-if="chatContent"
           style="height: calc( 100% - 15px);overflow: scroll;overflow-x: hidden;">
        <div v-for="(item,index) in chatContent" :key="index" style="margin-top: 5px">
          <div :class="item.userId!==uid?left_head_box:right_head_box" style="background-color: white">
            <img :src="item.avatar" class="myHeadIcon"/><br>
            <span style="background-color: white;font-size: smaller;color: grey">{{item.name}}</span>
          </div>
          <div class="content_view_box">
            <!--      方框前的三角形-->
            <span :class="item.userId!==uid?left_triangle:right_triangle"></span>
            <div :class="item.userId!==uid?left_msg_box:right_msg_box">{{item.content}}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="to_bottom" id="to_bottom" @click="updateView(chatContent.length)">
      <img src="~static/img/chat/bottom.png" height="20" width="20"/>
    </div>
    <div class="chat_input">
      <!--      <div contenteditable="true" class="input_box" id="input_box" style="margin-right: 1px"-->
      <!--           @keyup.enter="sendFun"></div>-->
      <div contenteditable="true" class="input_box" id="input_box" style="margin-right: 1px"></div>
      <button class="send_bt" @click="sendGroupMessage">发送</button>
    </div>
  </div>
</template>
<script>
  import {XHeader, TransferDom} from 'vux'
  import {mapState} from 'Vuex'
  import group from 'api/group'
  import SockJS from 'sockjs-client'
  import Stomp from 'stompjs'
  import chat from 'api/chat'

  export default {
    name: 'G_group_chat',
    components: {
      XHeader,
    },
    data () {
      return {
        alertText: '',
        isShowAlert: false,
        chatContent: [],
        groupName: '',
        uid: '',//登陆者id
        uName: '',
        messageInput: '',

        //控制每条消息的显示样式
        left_head_box: 'left_head_box',
        right_head_box: 'right_head_box',
        left_triangle: 'left_triangle',
        right_triangle: 'right_triangle',
        left_msg_box: 'left_msg_box',
        right_msg_box: 'right_msg_box',

        stompClient: null,

        groupMemberMap: [],
      }
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo
      }),
      ...mapState(['isGroupOwner', 'isGroupAdmin', 'groupPresent']),
    },
    mounted () {
      this.connect()
      console.log('群详情', this.groupPresent)
      let wholeName = this.groupPresent.detail.groupName
      this.groupName = wholeName.slice(wholeName.lastIndexOf('-') + 1)
      this.groupMemberMap = this.$store.state.memberMap
      console.log('对应关系', this.groupMemberMap)
    },
    directives: {
      TransferDom
    },
    watch: {
      chatContent (val) {
        let messageArea = document.querySelector('#message_box')
        const heightSpace = messageArea.scrollHeight - messageArea.scrollTop
        console.log('高度差：' + heightSpace + '，屏高' + messageArea.clientHeight)
        if (heightSpace > messageArea.clientHeight - 1 && heightSpace < messageArea.clientHeight + 1) {
          console.log('进来了进来了进来了')
          this.updateView(val.length)
        } else {
          this.newMsgNotice()
        }
      }
    },
    methods: {
      back () {
        this.$router.go(-1)
      },
      showAlert (alertText) {
        this.isShowAlert = true
        this.alertText = alertText
      },
      closeTip () {
        this.isShowAlert = false
        this.alertText = ''
      },
      toGroupMemberPage () {
        this.$router.push({name: 'G_group_member'})
      },
      connect () {
        // console.log('个人信息', this.userInfo)
        this.uid = this.userInfo.userId
        // console.log('12111111111111112', this.uid)
        const userName = this.userInfo.detail.name
        // console.log('用户名', userName)
        if (userName) {
          console.log('建立连接')
          const socket = new SockJS('http://wsn2019.club:8085/chat')
          this.stompClient = Stomp.over(socket)
          this.stompClient.connect({}, this.onConnected, this.onError)
        }
      },
      async onConnected () {
        console.log('连接中')
        // console.log('状态', this.stompClient.status)
        const allGroups = await group.getGroupsBeIn()
        // console.log('所有群', allGroups)
        if (allGroups.code === 1) {
          allGroups.data.forEach(item => {
            const gid = item.groupId
            // Subscribe to the Public Topic
            // TODO 对于该用户的每个群，都订阅一下，比如有群1,2,3，则
            this.stompClient.subscribe('/topic/' + gid, this.onMessageReceived)
          })
        }

        // 接下来是订阅自己的账号，假设该用户id是123
        // const uid = this.userInfo.userId
        // console.log(uid)
        // Tell your username to the server
        // this.stompClient.send('/app/chat.addUser',
        //   {},
        //   JSON.stringify({sender: this.userInfo.userId, type: 'JOIN'})
        // )
        await this.getHistoryLogs()
      },
      onError () {
        this.showAlert('Could not connect to WebSocket server. Please refresh this page to try again!')
      },
      sendGroupMessage () {
        const content_box = document.getElementById('input_box')
        const messageContent = content_box.textContent

        if (messageContent && this.stompClient) {
          const chatMessage = {
            sender: this.userInfo.userId,
            content: messageContent,
            type: 'GROUP',
            receiver: this.groupPresent.groupId
          }

          this.stompClient.send('/app/chat.sendGroupMessage', {}, JSON.stringify(chatMessage))
          content_box.textContent = ''
        }
      },
      onMessageReceived (payload) {
        // console.log('服务器返回信息',payload
        const msgBody = JSON.parse(payload.body)
        console.log('信息接收到了', msgBody)
        const msg = {
          userId: Number(msgBody.sender),
          name: this.getNameById(msgBody.sender),
          content: msgBody.content,
          avatar: this.getAvatarById(msgBody.sender)
        }
        this.chatContent.push(msg)
      },
      getNameById (idString) {
        const id = Number(idString)
        for (let i = 0; i < this.groupMemberMap.length; i++) {
          if (id === this.groupMemberMap[i].id) {
            return this.groupMemberMap[i].name
          }
        }
      },
      getAvatarById (idString) {
        const id = Number(idString)
        for (let i = 0; i < this.groupMemberMap.length; i++) {
          if (id === this.groupMemberMap[i].id) {
            return this.groupMemberMap[i].avatar
          }
        }
      },
      updateView (msgCont) {
        console.log('消息个数', msgCont)
        let timer = setTimeout(function () {
          const numbers = $('#message_box>div').length
          console.log('div个数', numbers)
          if (msgCont === numbers) {
            console.log('相等了')
            let messageArea = document.querySelector('#message_box')
            messageArea.scrollTop = messageArea.scrollHeight

            let notice = document.getElementById('to_bottom')
            notice.style.display = 'none'

            clearInterval(timer)
          }
        }, 50)
      },
      newMsgNotice () {
        let notice = document.getElementById('to_bottom')
        notice.style.display = 'block'
      },
      sendFun () {
        this.sendGroupMessage()
      },
      getHistoryLogs () {
        console.log('进来看聊天记录了')
        //异步处理方式
        const groupId = this.groupPresent.groupId
        chat.getGroupHistoryLogs(groupId).then(result => {
          if (result.code === 1) {
            result.data.forEach(item => {
              const msg = {
                userId: Number(item.sender),
                name: this.getNameById(item.sender),
                content: item.content,
                avatar: this.getAvatarById(item.sender)
              }
              this.chatContent.push(msg)
            })
          }
          console.log('结结果111', result)
        }).catch(function (error) {
          console.log('错错错错误', error)
        })

        //await方式

        // const result = await chat.getGroupHistoryLogs(groupId)
        // if (result.code===1){
        //   result.data.forEach(item=>{
        //     const msg = {
        //       userId: Number(item.sender),
        //       name: this.getNameById(item.sender),
        //       content: item.content,
        //       avatar: this.getAvatarById(item.sender)
        //     }
        //     this.chatContent.push(msg)
        //   })
        // }
        // console.log('1111111', result)
      }
    }
  }
</script>
<style scoped>

  * {
    -webkit-user-select: text;
  }

  .mainBg {
    margin-top: 46px;
    height: 100%;
    background: rgb(245, 245, 245);
  }

  .chat_view {
    height: 100%;
    width: 100%;

    /*background-color: red;*/
  }

  .message_box {
    width: 100%;
    background-color: white;
    padding: 0 10px;
    /*padding-bottom: 10px;*/
  }

  .chat_input {
    min-height: 70px;
    height: auto;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    background-color: white;
    vertical-align: bottom;
    border-top: #b2b2b2 solid 1px;
  }

  .input_box {
    display: inline-block;
    width: 65%;
    height: auto;
    min-height: 2rem;
    max-height: 10em;
    overflow: auto;
    padding: 5px 15px;
    margin: 10px;
    background-color: rgba(240, 248, 255, .6);
    border-radius: 20px;
    border: #b2b2b2 solid 1px;
  }

  .send_bt {
    display: inline-flex;
    /*width: 60px;*/
    line-height: 4rem;
    height: 4rem;
    text-align: center;
    vertical-align: top;
    border: 0;
    outline: 0;
    color: #35495E;
    background-color: white;
    font-size: 1.2rem;
  }

  .myHeadIcon {
    display: inline-block;
    width: 50px;
    height: 50px;
    margin-top: 0;
  }

  .content_view_box {
    display: inline-block;
    vertical-align: top;
    line-height: 20px;
    width: calc(100% - 80px);
    margin-right: 10px;
  }

  .left_head_box {
    display: inline-block;
    width: 50px;
    height: auto;
    padding: 0;
    text-align: center;
    margin-left: 5px;
    border: 0;
    background-color: rgb(245, 245, 245);
  }

  .left_triangle {
    display: inline-block;
    margin-left: -10px;
    margin-top: 10px;
    height: 0;
    width: 0;
    border: 10px solid transparent;
    border-right: 10px solid #faebcc;
  }

  .left_msg_box {
    display: inline-flex;
    padding: 10px;
    margin-left: -7px;
    background-color: #faebcc;
    border-radius: 5px;
    max-width: 85%;
    word-wrap: break-word;
    word-break: break-all;
  }

  .right_head_box {
    /*float: right;*/
    display: inline-block;
    margin-left: 80%;
    margin-right: 15px;
    width: 50px;
    height: auto;
    padding: 0;
    text-align: center;
    border: 0;
    background-color: rgb(245, 245, 245);
  }

  .right_triangle {
    float: right;
    margin-right: 1px;
    display: inline-block;
    /*margin-left: calc( 80% - 5px);*/
    margin-top: -60px;
    height: 0;
    width: 0;
    border: 10px solid transparent;
    border-left: 10px solid #c0e5f7;
  }


  .right_msg_box {
    display: inline-flex;
    margin-top: -65px;
    float: right;
    margin-right: calc(1% + 15px);
    /*margin-left: calc( 80% - 8px);*/
    padding: 10px;
    /*background-color: white;*/
    border-radius: 5px;
    max-width: 85%;
    word-wrap: break-word;
    word-break: break-all;
    background-color: #c0e5f7;
  }

  .content_time {
    margin: 5px;
    text-align: center;
    color: #b2b2b2;
    /*font-family: "微軟正黑體 Light";*/
    font-size: small;
  }

  .to_bottom {
    float: bottom;
    position: fixed;
    bottom: 75px;
    z-index: 999;
    left: 20px;
    display: none;
  }

  div {
    outline: none;
  }
</style>
